#include "tcpsocket.h"

#include <iostream>
#include <string.h>
#include "config.h"
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <sys/types.h>

#include "eventloop.h"

TcpSocket::TcpSocket(int fd, EventLoop *loop, ThreadPool *pool)
{
    m_fd = fd;
    m_evLoop = loop;
    m_tdPool = pool;

    ::bzero(m_recvBuff, BUFF_SIZE);
    ::bzero(m_sendBuff, BUFF_SIZE);
}

TcpSocket::~TcpSocket()
{
    ::close(m_fd);
}

void TcpSocket::createRecvCallback(RecvCallback cb)
{
    m_recvFunc = std::move(cb);
}

void TcpSocket::sendData(const char *msg)
{
    m_sendQueue.push(msg);
    m_evLoop->mdfEvent(m_fd,EPOLLOUT);
}

void TcpSocket::handleRead()
{
    ::bzero(m_recvBuff, BUFF_SIZE);
    int res = ::read(m_fd, m_recvBuff, BUFF_SIZE);
    if(res == -1)
    {
        ::perror("read error:");
        ::close(m_fd);
        m_evLoop->delEvent(m_fd,EPOLLIN);
    }else if(res == 0)
    {
        ::fprintf(stderr,"client close,fd=%d\n",m_fd);
        ::close(m_fd);
        m_evLoop->delEvent(m_fd,EPOLLIN);
    }else
    {
        m_recvFunc(m_recvBuff);
    }
}
void TcpSocket::handleWrite()
{
    int nwrite = 0;
    ::bzero(m_sendBuff, BUFF_SIZE);
    ::strcpy(m_sendBuff, m_sendQueue.front().c_str());
    m_sendQueue.pop();
    while(nwrite != ::strlen(m_sendBuff))
    {
        nwrite += ::write(m_fd, m_sendBuff+nwrite, strlen(m_sendBuff)-nwrite);
        if(nwrite == -1)
        {
            ::perror("write error:");
            ::close(m_fd);
            break;
        }
    }
    m_evLoop->mdfEvent(m_fd,EPOLLIN);
}
